class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.max_num = 1

        def search(node, value, num):
            if node:
                now_value = node.val
                if num == 0:
                    search(node.left, now_value, 1)
                    search(node.right, now_value, 1)
                else:
                    if now_value == value + 1:
                        new_num = num + 1
                        if new_num > self.max_num:
                            self.max_num = new_num
                    else:
                        new_num = 1
                    search(node.left, now_value, new_num)
                    search(node.right, now_value, new_num)
        search(root, 0, 0)

        return self.max_num
